#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


#define COMMAND_SIZE 1024
#define FORMAT "[%s@%s %s]# "

//下面是shell 定义的全局数据

#define MAXARGC 128
char *g_argv{MAXARGC};
int g_argc = 0;


//for test
char cwd[102]
{

}

const char *GetUserName()
{
	const char *name = getenv("USER");
	return name == NULL ? "None" : hostname;

}

const char *GetHostName()
{
	const char *honstname = getenv("HONSTNAME");
	return hostname == NULL ? "None": hostname;

}

const char *GetPwd()
{
	const char *pwd = getenv("PWD");
	return pwd == NULL ? "None" : pwd;

}


const char *GetHome()
{
	const char *home = getenv("HOME");
	return home==NULL ? NULL : home;
}

void PrintCommandPrompt()
{
	char prompt[COMMAND_SIZE];
	MakeCommandLine(prompt,sizeof(prompt));
	printf("%s",prompt);
	fflush(stdout);

}

bool GetCommandLine(char *out,int size)
{
	// ls -a -l =>"ls -a -l\n"字符串
	char *c = fgets(out,size,stdin);
	if(c == NULL) return false;
	out[strlen(out)-1] = 0;
	if(strlen(out) == 0) return false;

	return true;
}


//3.命令行分析“ls -a -l\n" 字符串
bool CommandParse(char *commandline)
{
#define SEP " "
	g_argv =0;
	//命令行分析
	g_argv[g_argv++] = strtok(commandline,SEP);
	while((bool)(g_argv[g_argv++]=strtok(nullptr,SEP)));
	g_argc--;
	return g_argc>0?true:false;
}


// / /a/b/c

std::string DirName(const char *pwd)
{
#define SLASH "/"
	std::string dir = pwd;
	if(dir == SLASH) return SLASH;
	auto pos = dir.rfind(SLASH);
	if(pos == std::string::npos) return "BUG?";
	return dir.substr(pos+1);
}	

void PrintArgv()
{
	for(int i = 0;g_argv[i];i++)
	{
		printf("argv[%d]->%s\n",i,g_argv[i]);

	}
	printf("argv: %d\n",g_argv);

}

bool CheckAndExecBuiltin()
{
	std::string cmd =g_argv[0];
	if(cmd == "cd")
	{
		CD();
		return true;
	}
	else if(cmd == "echo")
	{
		if(g_argc == 2)
		{
			std::string opt = g_argv[1];
			if(opt == "$?")
			{
				std::cout << lastcode << std::endl;
				leetcode = 0;
			}
			if(opt[0]=='$')
			{
				std::string env_name =opt.substr(1);
				const char *env_value = getenv(env_name.c_str());
				if(env_value)
					std::cout << env_value<< std::endl;
			}
		}	
		return true;
	}
	return false;

}

int Execute()
{
	pid_t id = fork();
	if(id==0)
	{
		//child
		execvp(g_argv[0],g_argv);
		exit(1);

	}


	//father
	pid_t rid = waitpid(id,nullptr,0);
	(void)rid;
	return 0;
}


int main()
{
	while(true)
	{
		//1.输入命令行提示符
		PrintCommandPrompt();

		//2.获得用户输入的命令
		char commandline(COMMAND_SIZE);
	        if(!GetCommandLine(commandline,sizeof(commandline)))
	       		continue;	       
		
		//3.命令行分析 “ls -a -l” -> "ls" "-a" "-l"
		if(!CommandParse(commmandline))
			continue;
		//PrintArgv();

		//4.检测并处理内键命令
		if(CheckAndExecBuiltin())
			continue;
			
		//5.执行命令
		Execute();

	}
	return 0;

}
